package com.rongke.web;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.rongke.commons.JsonResp;
import com.rongke.model.Goods;
import com.rongke.model.IndexGroup;
import com.rongke.service.GoodsService;
import com.rongke.service.IndexGroupService;
import com.rongke.utils.StringUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @IndexGroupController
 * @主页分组标签Controller
 * @version : Ver 1.0
 */
@RestController
@RequestMapping(value="/api/indexGroup")
@Transactional
@CrossOrigin(origins = "*", maxAge = 3600)
public class IndexGroupController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private IndexGroupService indexGroupService;
    @Autowired
    private GoodsService goodsService;

    /**
     * @添加主页分组标签
     * @param indexGroup
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/add", method = RequestMethod.POST)
    public JsonResp addIndexGroup(@RequestBody IndexGroup indexGroup){
        log.debug("添加主页分组标签");
        if(StringUtil.isEmpty(indexGroup.getTitle()))
            return JsonResp.toFail("参数不能为空！");
        indexGroupService.insert(indexGroup);
        return JsonResp.ok(indexGroup);
    }

    /**
     * @修改主页分组标签
     * @param indexGroup
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/update", method = RequestMethod.POST)
    public JsonResp updateIndexGroup(@RequestBody IndexGroup indexGroup){
        log.debug("修改主页分组标签");
        indexGroupService.updateById(indexGroup);
        return JsonResp.ok(indexGroup);
    }

    /**
     * @删除分组
     * @param datas
     * @return
     */
    @RequestMapping(value="/delete",method =RequestMethod.POST)
    public JsonResp deleteIndexGroup(@RequestBody Map<String, Object> datas){
        Long id=Long.parseLong((String)datas.get("id"));
        log.debug("删除分组");
        indexGroupService.deleteById(id);
        //确定要级联删除子节点数据
        if(StringUtil.isNotEmpty((String)datas.get("rec"))){
            EntityWrapper<IndexGroup> ew =new EntityWrapper<>();
            ew.eq("pid",id);
            indexGroupService.delete(ew);
        }
        return JsonResp.ok("删除分组成功");
    }

    /**
     * @根据id查找主页分组标签
     * @param id
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/selectOne", method = RequestMethod.GET)
    public JsonResp selectIndexGroup(Long id){
        log.debug("查找主页分组标签");
        IndexGroup indexGroup = indexGroupService.selectById(id);
        return JsonResp.ok(indexGroup);
    }

    /**
     * @根据条件查找主页分组标签
     * @param indexGroup
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/selectByCondition", method = RequestMethod.POST)
    public JsonResp selectIndexGroupByCondition(@RequestBody IndexGroup indexGroup){
        log.debug("根据条件查找主页分组标签");
        if(indexGroup==null)
            return JsonResp.toFail("参数不能为空");
        List<IndexGroup> indexGroupList=indexGroupService.selectByCondition(indexGroup);
        return JsonResp.ok(indexGroupList);
    }

    /**
     * 获取某产品线下一级标签分组列表
     * @param groupType 分类所属产品线（0 蜜哆哆 1 蜜雅阁 2 品牌馆）
     * @return
     */
    @RequestMapping(value = "/getFirstGroupList", method = RequestMethod.GET)
    public JsonResp getFirstGroupList(int groupType) {
        log.debug("获取一级标签分组列表");
        EntityWrapper<IndexGroup> ew=new EntityWrapper<>();
        ew.eq("group_type",groupType).isNull("pid");
        ew.orderBy("sort",false);
        List<IndexGroup> firstGroupList = indexGroupService.selectList(ew);
        return JsonResp.ok(firstGroupList);
    }

    /**
     * 根据一级分组查找二级分组列表（一级分组就定好了产品线）,带一级分组图片
     * @param pid
     * @return
     */
    @RequestMapping(value = "/selectSecondGroupByPid", method = RequestMethod.GET)
    public JsonResp selectSecondGroupByPid(String pid) {
        log.debug("根据一级分组查找二级分组列表");
        if(StringUtil.isEmpty(pid))
            return JsonResp.toFail("一级分组id不能为空！");
        IndexGroup indexGroup=indexGroupService.selectById(pid);
        EntityWrapper<IndexGroup> ew=new EntityWrapper<>();
        ew.eq("pid",pid);
        List<IndexGroup> igList= indexGroupService.selectList(ew);
        Map<String,Object> map=new HashMap<>();
        map.put("bannerPic",indexGroup.getPictureUrl());
        map.put("secGroupList",igList);
        return JsonResp.ok(map);
    }

    /**
     * 获取某产品线下的全部一级分组附带二级分组
     * @param groupType 产品线（0 蜜哆哆 1 蜜雅阁 2 品牌馆）
     * @return
     */
    @RequestMapping(value = "/getAllGroup",method = RequestMethod.GET)
    public JsonResp getAllGroup(int groupType){
        log.debug("获取某产品线下的全部一级分组附带二级分组");
        EntityWrapper<IndexGroup> ew=new EntityWrapper<>();
        //取一级分组
        ew.eq("group_type",groupType).isNull("pid");
        List<IndexGroup> firstGroupList = indexGroupService.selectList(ew);
        //取二级分组
        EntityWrapper<IndexGroup> ew2= new EntityWrapper<>();
        ew2.eq("group_type",groupType).isNotNull("pid");
        List<IndexGroup> secondGroupList=indexGroupService.selectList(ew2);
        Map<String,List<IndexGroup>> indexGroupMap=new HashMap<>();
        //组装map
        indexGroupMap.put("firstGroupList",firstGroupList);
        indexGroupMap.put("secondGroupList",secondGroupList);
        return JsonResp.ok(indexGroupMap);
    }

    /**
     * 获取分组树json
     * @param cateType 分类所属产品线（0 蜜哆哆 1 蜜雅阁 2 品牌馆）
     * @return
     */
    @CrossOrigin(origins = "*", maxAge = 3600)
    @RequestMapping(value = "/getTree", method = RequestMethod.GET,produces = "text/plain;charset=UTF-8")
    public String getTree(Integer cateType) {
        log.debug("获取分组树json");
        if(null==cateType)
            cateType=0;
        if(cateType!=0&&cateType!=1&cateType!=2)
            return "参数出错";
        EntityWrapper<IndexGroup> ew=new EntityWrapper();
        ew.eq("group_type",cateType);
        ew.orderBy("sort",false);
        List<IndexGroup> groupList=indexGroupService.selectList(ew);
        List list = new ArrayList();
        for (IndexGroup c:groupList) {
            Map map1 = new HashMap();
            map1.put("id", c.getId());
//            如果父id为空，则为一级分类，即树的一级节点
            if (null==c.getPid()) {
                map1.put("parent", "#");
            } else map1.put("parent",c.getPid());
            map1.put("text", c.getTitle());
            map1.put("subtitle", c.getSubtitle());
            map1.put("picture_url",c.getPictureUrl());
            map1.put("sort",c.getSort());
            map1.put("is_homepage",c.getIsHomepage());
            list.add(map1);
        }
        String jsonObject = JSON.toJSONString(list, true);
        log.debug(jsonObject);
        return jsonObject;
    }



    /**
     * 根据一级分组获取二级分组以及二级分组下的商品列表
     * @return  id  一级分组id
     */
    @RequestMapping(value = "/findGroupGoodsList", method = RequestMethod.GET)
    public JsonResp findGroupGoodsList(Long pid,Page page) {
        log.debug("根据一级分组获取二级分组以及二级分组下的商品列表");
        EntityWrapper<IndexGroup> ew=new EntityWrapper<>();
        ew.eq("pid",pid);
        List<IndexGroup> igList= indexGroupService.selectList(ew);
        IndexGroup pic=indexGroupService.selectById(pid);
        List<Map> maps=new ArrayList<>();
        Page<Goods> goodsList=null;
        for(int i=0,y=igList.size();i<y;i++){
            IndexGroup indexGroup=igList.get(i);
            EntityWrapper<Goods> ew_goods=new EntityWrapper<>();
            ew_goods.eq("index_group_id",indexGroup.getId());
            ew_goods.orderBy("gmt_datetime",false);
            goodsList=goodsService.selectPage(page,ew_goods);
            List<Goods> goodsList1=goodsList.getRecords();
            Map map=new HashMap();
            map.put("indexGroup",indexGroup);
            map.put("goodsList",goodsList1);
            maps.add(map);
        }
        Map data=new HashMap();
        data.put("pic",pic);
        data.put("maps",maps);
        return JsonResp.ok(data);
    }


}
